package com.yunyao.common.web.util;

import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * EnumUtils
 * @author chenyejian
 * @date 2024-07-21
 */
public class EnumUtils {
    /**
     * 根据类名获取枚举类转成的map
     */
//    static final String prefix_className = "com.yunyao.common.constant.enums.";
    public static Map<String, String> generateKeyValueMap(String className) {
        try {
//            className = prefix_className + className;
            Class<?> clazz = Class.forName(className);
            if (!clazz.isEnum()) {
                throw new IllegalArgumentException(className + " is not an enum type.");
            }

            Map<String, String> keyValueMap = new LinkedHashMap<>(); // 使用LinkedHashMap来保持顺序
            for (Object enumConstant : clazz.getEnumConstants()) {
                Field typeField = clazz.getDeclaredField("type");
                Field descriptionField = clazz.getDeclaredField("description");
                typeField.setAccessible(true);
                descriptionField.setAccessible(true);
                Object typeValue = typeField.get(enumConstant);
                String type = "";
                if (typeValue instanceof String stringType) {
                    type = stringType;
                }
                if (typeValue instanceof Integer intType) {
                    type = ConvertUtil.null2String(intType);
                }
                String description = (String) descriptionField.get(enumConstant);
                keyValueMap.put(type, description);
            }
            return keyValueMap;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Class not found: " + className, e);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException("Error accessing fields of " + className, e);
        }
    }


}
